package com.example.util;

import com.example.config.AppConfig;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 1.启动SpringMVC 容器 类注入到Spring中
 * 2.注入配置类
 * 3. 将DispatcherServlet 注入到 serlvet容器中
 * 4.设置优先级 优先级最高表示 最早被加载
 * 5.填写url路径映射
 *
 * @author kangshuai
 */
public class MyWebApplicationInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {

        // 1.启动SpringMVC 容器 类注入到Spring中
        AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();
        // 2.注入配置类
        annotationConfigWebApplicationContext.register(AppConfig.class);
        annotationConfigWebApplicationContext.refresh();

        // 3. 将DispatcherServlet 注入到 serlvet容器中
        DispatcherServlet servlet = new DispatcherServlet(annotationConfigWebApplicationContext);
        ServletRegistration.Dynamic registration = servletContext.addServlet("app", servlet);
        // 4.优先级最高表示 最早被加载
        registration.setLoadOnStartup(1);
        // 5.填写url路径映射
        registration.addMapping("/app/*");
    }
}
